package com.ffapp.helper.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisFragment;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.bean.ParamListData;
import com.ffapp.helper.util.CountDown;
import com.ffapp.helper.util.RulerUtil;
import com.ffapp.helper.util.SoftKeyBoardListener;
import com.ffapp.helper.util.SubstringUtil;
import com.ffapp.helper.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.CheckUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.TimeUtils;

public class TerminalFragment extends BasisFragment { static TerminalFragment fragment;

    public static TerminalFragment newInstance() {
        if (fragment == null) {
            fragment = new TerminalFragment();
        }
        return fragment;
    }


    MySharedPreferences mSp;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> terminalList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;
    private boolean isFinish = false;
    private boolean isDestroy = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private PopHandle popHandle;

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < terminalList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                        } else {
                            originalList.clear();
                            originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {}); // Json 转List
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if (!isFinish && !isDestroy) {
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_terminal);
        mSp = new MySharedPreferences(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
        isDestroy = false;
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        terminalList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    public void setList(String sMsgObjString, int type) {
        terminalList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {
            //设备时间
            String excclk = SubstringUtil.subString(sMsgObjString, "+EXCCLK:");
            terminalList.add(new ParamListData("设备时间", 4, "" + excclk, "AT+EXCCLK"));
            //通信协议
            String proValue = SubstringUtil.subString(sMsgObjString, "Pro:");
            ArrayList<String> commProtocolList = new ArrayList<>();
            commProtocolList.add("水文ASCII");
            commProtocolList.add("水文HEX");
            terminalList.add(new ParamListData("通讯协议", 1, "" + proValue, commProtocolList, "AT+PRO"));
            //工作模式
            String workModeValue = SubstringUtil.subString(sMsgObjString, "Work Mode:");
            if (workModeValue.equals("0")) {
                workModeValue = "自报模式";
            } else if (workModeValue.equals("1")) {
                workModeValue = "兼容模式";
            }
            ArrayList<String> sworkModelList = new ArrayList<>();
            sworkModelList.add("自报模式");
            sworkModelList.add("兼容模式");
            terminalList.add(new ParamListData("工作模式", 1, workModeValue, sworkModelList, "AT+MOD"));
            //调试信息等级
            String debugLevel = SubstringUtil.subString(sMsgObjString, "Debug Level:");
            ArrayList<String> debugLevelList = new ArrayList<>();
            debugLevelList.add("0");
            debugLevelList.add("1");
            debugLevelList.add("2");
            terminalList.add(new ParamListData("调试信息等级", 1, "" + debugLevel, debugLevelList, "AT+DEBUG"));
            //遥测站分类码
            String tcode = SubstringUtil.subString(sMsgObjString, "Term Code:");
            List<String> termCodeList = Arrays.asList(getResources().getStringArray(R.array.code));
            terminalList.add(new ParamListData("遥测站分类码", 1, "" + RulerUtil.getTCode(tcode), termCodeList, "AT+TCODE"));
            //遥测站地址
            String termAddrValue = SubstringUtil.subString(sMsgObjString, "Term Addr:");
            terminalList.add(new ParamListData("遥测站地址", 2, "" + termAddrValue, "AT+TADD", "",2));
            //中心站地址
            String sCenterAddress1 = "";
            String sCenterAddress2 = "";
            String sCenterAddress3 = "";
            String sCenterAddress4 = "";
            sCenterAddress1 = SubstringUtil.subString(sMsgObjString, "Center Code 0:");
            sCenterAddress2 = SubstringUtil.subString(sMsgObjString, "Center Code 1:");
            sCenterAddress3 = SubstringUtil.subString(sMsgObjString, "Center Code 2:");
            sCenterAddress4 = SubstringUtil.subString(sMsgObjString, "Center Code 3:");
            String address = null;
            address = HexUtil.decimalDigitsToHex(sCenterAddress1) + HexUtil.decimalDigitsToHex(sCenterAddress2) + HexUtil.decimalDigitsToHex(sCenterAddress3) + HexUtil.decimalDigitsToHex(sCenterAddress4);
            terminalList.add(new ParamListData("中心站地址", 2, "" + address, "AT+MADD", "",2));
            //通信密码
            String commPwdValue = SubstringUtil.subString(sMsgObjString, "Comm pwd:");
            terminalList.add(new ParamListData("通信密码", 2, commPwdValue, "AT+COMPWD", "",2));
            //本地密码
            String localPwd = SubstringUtil.subString(sMsgObjString, "Local pwd:");
            terminalList.add(new ParamListData("本地密码", 2, localPwd, "AT+LOCPWD", "",2));
            //通信站识别号
            String commId = SubstringUtil.subString(sMsgObjString, "Comm ID:");
            terminalList.add(new ParamListData("通信站识别号", 2, commId, "AT+COMMID", ""));
            //ModBus设备地址
            String modbusAdd = SubstringUtil.subString(sMsgObjString, "Modbus Add:");
            terminalList.add(new ParamListData("ModBus设备地址", 2, modbusAdd, "AT+MBADD", "",2));
            //定时上报时间
            String reportIntValue = SubstringUtil.subString(sMsgObjString, "Report Int:");
            terminalList.add(new ParamListData("定时上报时间（0~1440分）", 2, reportIntValue, "AT+RPTINT", "分",0,1440,2));
            //加报报时间
            String alarmReportIntValue = SubstringUtil.subString(sMsgObjString, "Alarm Report Int:");
            terminalList.add(new ParamListData("加报报时间隔（0~59分）", 2, alarmReportIntValue, "AT+AINT", "分",0,59,2));
            //均匀时段上报
            String uniform = SubstringUtil.subString(sMsgObjString, "Uniform Report Int:");
            terminalList.add(new ParamListData("均匀时段上报（0~24小时）", 2, uniform, "AT+SLERT", "小时",0,24,2));
            //小时报开关
            String hourReportSw = SubstringUtil.subString(sMsgObjString, "HourReportSW:");
            List<String> openOrCloseList = Arrays.asList(getResources().getStringArray(R.array.openOrClose));
            terminalList.add(new ParamListData("小时报开关", 1, "" + getOperOrClose(hourReportSw), openOrCloseList, "AT+SLHOURRPT"));
            //报文补报开关
            String redeemSw = SubstringUtil.subString(sMsgObjString, "RedeemReportSW:");
            terminalList.add(new ParamListData("报文补报开关", 1, "" + getOperOrClose(redeemSw), openOrCloseList, "AT+SLREDEEM"));
            //时段雨量配置
            String minPn = SubstringUtil.subString(sMsgObjString, "check min pn:");
            terminalList.add(new ParamListData("时段雨量配置", 2, minPn, "AT+CHKMINPN", "0-59",0,59,2));
            //雨量日起始时间
            String rainDay = SubstringUtil.subString(sMsgObjString, "Rain Day Start Time:");
            terminalList.add(new ParamListData("雨量日起始时间", 2, rainDay, "AT+SLRS", "0-23",0,23,2));

            switch (mSp.getDevType()){
                case"F-LD100":
                    //液位基值
                    String ldRange = SubstringUtil.subString(sMsgObjString, "LD range:");
                    terminalList.add(new ParamListData("液位基值", 2, ldRange, "AT+LDRANGE", "-50~50"));
                    //液位量程
                    String ldSpan = SubstringUtil.subString(sMsgObjString, "LD span:");
                    terminalList.add(new ParamListData("液位量程", 2, ldSpan, "AT+LDSPAN", "<70m"));
                    break;
            }

            if (type == Constants.AT_FROM_DEVICE) {
//                ArrayList<ParamListData> n = (ArrayList<ParamListData>) JSON.parseArray(a,ParamListData.class); // Json 转List
                originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {
                }); // Json 转List
            }
        }

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);

        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return terminalList == null ? 0 : terminalList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                ParamListData terminalListData = terminalList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        editText.setInputType(terminalListData.getinputType_REAL());
                        editText.setVisibility(View.VISIBLE);
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setEnabled(false);//不可编辑
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setInputType(terminalListData.getinputType_REAL());
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setEnabled(true);//可编辑
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 3:  // 开关按钮
                        switch (terminalListData.getValue()) {
                            case "0":
                                switchBtn.setChecked(false);
                                break;
                            case "1":
                                switchBtn.setChecked(true);
                                break;
                        }
                        imgSpanner.setVisibility(View.GONE);
                        tvUnit.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setVisibility(View.INVISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        switchBtn.setVisibility(View.VISIBLE);
                        switchBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                                if (isChecked == true) {
                                    editText.setText("1");
                                } else {
                                    editText.setText("0");
                                }
                            }
                        });
                        break;
                    case 4:  // 同步按钮
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setEnabled(false);//不可编辑
                        editText.setVisibility(View.VISIBLE);
                        tvSynchro.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 86:   //分隔作用
                        imgSpanner.setVisibility(View.GONE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.base_bg_white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = terminalList.get(curPosition);
                        data.setValue(s.toString());
                    }
                });
                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }

            @OnClick(R.id.tv_synchro)
            public void synchroTime(View v) {
                String time = TimeUtils.getTimeLongToStrByFormat(System.currentTimeMillis(), "yyyy/MM/dd,HH:mm:ss") + "," + Calendar.getInstance().getTime().getDay();
                editText.setText(time);
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, terminalList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(terminalList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });
    }

    public void initSettingSaveThred(final int position) {
        ParamListData paramListData = terminalList.get(position);
        if(!paramListData.isParamsOk(this)) return;

        String url = paramListData.getActionUrl(mContext);
        if (TextUtils.isEmpty(url) && !(paramListData.getName().equals("设备时间"))) {
            if(paramListData.getName().equals("通信站识别号")){
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
                return;
            }
            showToast(paramListData.getName() + "的值不能为空");
            dismissProgress();
            return;
        }

        ParamListData originalData = originalList.get(position);
        String originalurl = originalData.getActionUrl(mContext);
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        BleLog.d("TerminalFragment===============   " + paramListData.getName() + "通过");
        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    BleLog.d("TerminalFragment   " + paramListData.getName() + "下发设置发送成功");
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                BleLog.d("TerminalFragment   " + paramListData.getName() + "下发发送失败");
//                saveResult.append(paramListData.getName() + "下发失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }
        });


    }



    private String getOperOrClose(String key) {
        String value = "";
        switch (key) {
            case "0":
                value = "关闭";
                break;
            case "关闭":
                value = "0";
                break;
            case "1":
                value = "开启";
                break;
            case "开启":
                value = "1";
                break;

        }
        return value;
    }

    private String getEncrypt(String key) {
        String value = "";
        switch (key) {
            case "0":
                value = "不加密";
                break;
            case "不加密":
                value = "0";
                break;
            case "1":
                value = "加密";
                break;
            case "加密":
                value = "1";
                break;

        }
        return value;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        isFinish = true;
        BleUtils.stopNotify();
        mCountDownTimer.cancel();
    }

}
